package com.djl.crowd.util;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class CrowdUtil {


    /**
     * @param source 传入要加密的字符串
     * @return 加密后的数据
     * @desc md5加密工具
     */
    public static String md5Utils(String source) {
        // 1.判断source是否有效
        if (source.equals("") || source.length() == 0 || source == null) {
            // 2.不是有效字符串，抛出异常
            throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }

        try {
            // 3.获取MessageDigest对象
            String algorithm = "md5";
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);

            // 4.获取明文字符串对应的字节数组
            byte[] input = source.getBytes();
            // 5.执行加密
            byte[] outPut = messageDigest.digest(input);
            // 6.创建BigInteger对象
            int sigNum = 1;
            BigInteger bigInteger = new BigInteger(sigNum, outPut);
            // 7.按16进制将biginteger的值转换为字符串
            int radix = 16;
            // toUpperCase() 将所有字符转换为大写
            String encoded = bigInteger.toString(radix).toUpperCase();

            return encoded;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断请求是普通请求还是ajax请求
     *
     * @param request
     * @return
     */
    public static boolean judgeRequestType(HttpServletRequest request) {
        //获取请求消息头
        String acceptHandler = request.getHeader("Accept");
        String xRequestHeader = request.getHeader("X-Requested-With");

        return (acceptHandler != null && acceptHandler.contains("application/json"))
                ||
                (xRequestHeader != null && xRequestHeader.equals("XMLHttpRequest"));

    }

}
